package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"micros/api/params"
	"micros/golbal"
	"micros/inits"
	"micros/pkg"
	"net/http"
	"strconv"
	"time"
)

func SendSms(c *gin.Context) {
	var send params.Sms
	if err := c.ShouldBind(&send); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	count, err := golbal.Rdb.Get(inits.Ctx, "SmsCode"+send.Mobile).Int64()
	if count >= 3 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "同一手机号1分钟内最多发送3条验证码",
		})
	}

	code := rand.Intn(900000) + 100000

	sprintf := fmt.Sprintf("短信:%v", send.Mobile)
	golbal.Rdb.Set(inits.Ctx, strconv.Itoa(code), sprintf, time.Minute*3)
	golbal.Rdb.Incr(inits.Ctx, "SmsCode"+send.Mobile)
	golbal.Rdb.Expire(inits.Ctx, "SmsCode"+send.Mobile, time.Minute*1)
	sms, err := pkg.SendSms(send.Mobile, strconv.Itoa(code))
	if err != nil {
		return
	}
	if *sms.Body.Code != "OK" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  sms.Body.Message,
			"data": sms,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信发送成功",
	})
}
